package com.kim.logs.core.provider;

import com.kim.logs.bean.OperatorLog;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.index.query.QueryBuilders;
import org.zxp.esclientrhl.repository.ElasticsearchTemplate;

import java.util.List;

/**
 * @Project: ymdx-security-logs
 * @PackageName: com.ymdx.security.logs.core.provider
 * @FileName: EsAppendeServiceManager.java
 * @Description: The EsAppendeServiceManager is...
 * @Author: kimwu
 * @Time: 2020-10-30 14:56:01
 */
@Slf4j
public class EsAppendeServiceManager implements LogAppenderService {

    private ElasticsearchTemplate<OperatorLog, String> elasticsearchTemplate;

    private String sysCode;

    public EsAppendeServiceManager() {
    }

    public EsAppendeServiceManager(ElasticsearchTemplate<OperatorLog, String> elasticsearchTemplate, String sysCode) {
        this.elasticsearchTemplate = elasticsearchTemplate;
        this.sysCode = sysCode;
    }

    @Override
    public void append(OperatorLog operatorLog) {
        try {
            operatorLog.setSystem(sysCode);
            //幂等性校验
            List<OperatorLog> byTime = elasticsearchTemplate.search(QueryBuilders.termQuery("createTime", operatorLog.getCreateTime()), OperatorLog.class);
            if (byTime != null && byTime.size() != 0) {
                throw new RuntimeException("日志重复，拒绝写入");
            }
            elasticsearchTemplate.save(operatorLog);
        } catch (Exception e) {
            log.error("es写入日志失败 , 原因 ：{}", e.getMessage());
        }
    }
}
